package com.chensf.studydemo.common

import android.graphics.*
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.chensf.studydemo.R
import kotlinx.android.synthetic.main.fragment_avatar_demo.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AvatarDemo :Fragment(){
    private var textBgColor: Int = 0
    private var textColor: Int = 0
    private var imageBgColor: Int=0   //生成的组合图片的背景颜色

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_avatar_demo,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        textBgColor = ContextCompat.getColor(requireContext(),R.color.ct_contacts_avatar_bg_color)
        textColor = ContextCompat.getColor(requireContext(),R.color.ct_base_white)
        imageBgColor = ContextCompat.getColor(requireContext(),R.color.ct_multi_avatar_bg)
        button.setOnClickListener {
            foo3()
        }
    }

    private fun foo() {
        lifecycleScope.launch(Dispatchers.Main){
            val bitmap = withContext(Dispatchers.IO){
                val bitmap1 = getTextBitmap("欧")
                val bitmap2 = getTextBitmap("扎")
                val bitmap3 = getTextBitmap("克")
                val bitmap4 = getTextBitmap("牛")
                getCombineBitmap(listOf(bitmap1,bitmap2,bitmap3,bitmap4),400,0,30,imageBgColor)
            }
            imageView.setImageBitmap(bitmap!!)
        }
    }
    private fun foo2() {
        lifecycleScope.launch(Dispatchers.Main){
            val bitmap = withContext(Dispatchers.IO){
                val bitmap1 = getTextBitmap1("欧")
                val bitmap2 = getTextBitmap("扎")
                val bitmap3 = getTextBitmap("克")
                getCombineBitmap(listOf(bitmap1,bitmap2,bitmap3),400,0,30,imageBgColor)
            }
            imageView.setImageBitmap(bitmap!!)
        }
    }

    private fun foo3() {
        lifecycleScope.launch(Dispatchers.Main){
            val bitmap = withContext(Dispatchers.IO){
                getTextBitmap("欧克")
//                val bitmap2 = getTextBitmap("扎")
//                val bitmap3 = getTextBitmap("克")
//                getCombineBitmap(listOf(bitmap1,bitmap2,bitmap3),400,0,30,imageBgColor)
            }
            val list = mutableListOf<String>("1","2","3","4","5")
            list.shuffled().take(5).forEach {
                Log.e("foo", it)
            }
            Log.e("foo", "================================")
            imageView.setImageBitmap(bitmap)
        }
    }

    private fun drawRoundBitmap(
        canvas: Canvas,
        bitmap: Bitmap,
        left: Int,
        top: Int,
        size: Int,
        radius: Int
    ) {
        val mPaint = Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG)
        val bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        mPaint.shader = bitmapShader
        canvas.save()
        canvas.translate(left.toFloat(), top.toFloat())
        canvas.drawRoundRect(
            RectF(0F, 0F, size.toFloat(), size.toFloat()),
            radius.toFloat(),
            radius.toFloat(),
            mPaint
        )
        canvas.restore()
    }
    private fun drawRoundBitmap1(
        canvas: Canvas,
        bitmap: Bitmap,
        left: Int,
        top: Int,
        width: Int,
        height: Int,
        radius: Int
    ) {
        val mPaint = Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG)
        val bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        mPaint.shader = bitmapShader
        canvas.save()
        canvas.translate(left.toFloat(), top.toFloat())
        canvas.drawRoundRect(
            RectF(0F, 0F, width.toFloat(), height.toFloat()),
            radius.toFloat(),
            radius.toFloat(),
            mPaint
        )
        canvas.restore()
    }

    private fun getTextBitmap1(name: String): Bitmap {
        //截取后两个字
        val lastName = if (name.length >= 2) {
            name.substring(name.length - 2)
        } else {
            name
        }
        val size = 200F
        val bitmap = Bitmap.createBitmap(size.toInt(), size.toInt()*2, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        canvas.drawColor(textBgColor)
        if (!TextUtils.isEmpty(name)) {
            val textPaint = Paint()
            textPaint.isAntiAlias = true
            textPaint.color = textColor
            textPaint.style = Paint.Style.FILL
            textPaint.textAlign = Paint.Align.CENTER
//            textPaint.typeface = Typeface.create("sans-serif-light", Typeface.NORMAL)
            val textSize =
                if (lastName.toByteArray().size != lastName.length && lastName.length > 1) {
                    size * 1f / 2.5f
                } else {
                    size * 1f / 2
                }
            textPaint.textSize = textSize
            canvas.drawText(
                lastName,
                size / 2.toFloat(),
                size  - (textPaint.descent() + textPaint.ascent()) / 2,
                textPaint
            )
        }
        return bitmap
    }

    /**
     * 根据文字生成图片
     */
    private fun getTextBitmap(name: String): Bitmap {
        //截取后两个字
        val lastName = if (name.length >= 2) {
            name.substring(name.length - 2)
        } else {
            name
        }
        val size = 200F
        val bitmap = Bitmap.createBitmap(size.toInt(), size.toInt(), Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        canvas.drawColor(textBgColor)
        if (!TextUtils.isEmpty(name)) {
            val textPaint = Paint()
            textPaint.isAntiAlias = true
            textPaint.color = textColor
            textPaint.style = Paint.Style.FILL
            textPaint.textAlign = Paint.Align.CENTER
//            textPaint.typeface = Typeface.create("sans-serif-light", Typeface.NORMAL)
            val textSize =
                if (lastName.toByteArray().size != lastName.length && lastName.length > 1) {
                    size * 1f / 2.5f
                } else {
                    size * 1f / 2
                }
            textPaint.textSize = textSize
            canvas.drawText(
                lastName,
                size / 2.toFloat(),
                size / 2 - (textPaint.descent() + textPaint.ascent()) / 2,
                textPaint
            )
        }
        return bitmap
    }

    private fun getCombineBitmap(
        bitmapList: List<Bitmap>,
        size: Int,
        radius: Int,
        border: Int,
        @ColorInt backgroundColor: Int
    ): Bitmap? {
        return try {
            val result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(result)
            canvas.drawColor(backgroundColor)
            //START|MIDDLE|END留边界
            val scaleSize = (size - border) / 2
            val listSize = bitmapList.size
            when (listSize) {
                1 -> {
                    val _p11 = Bitmap.createScaledBitmap(bitmapList[0], scaleSize, scaleSize, false)
                    // 绘图
                    drawRoundBitmap(
                        canvas,
                        _p11,
                        size / 2 - scaleSize / 2,
                        size / 2 - scaleSize / 2,
                        scaleSize,
                        radius
                    )
                }
                2 -> {
                    // 比例缩放
                    val _p21 = Bitmap.createScaledBitmap(bitmapList[0], scaleSize, scaleSize, false)
                    val _p22 = Bitmap.createScaledBitmap(bitmapList[1], scaleSize, scaleSize, false)
                    // 绘图
                    drawRoundBitmap(
                        canvas,
                        _p21,
                        border,
                        size / 2 - scaleSize / 2,
                        scaleSize,
                        radius
                    )
                    drawRoundBitmap(
                        canvas,
                        _p22,
                        border * 2 + scaleSize,
                        size / 2 - scaleSize / 2,
                        scaleSize,
                        radius
                    )
                }
                3 -> {
                    val _p31 = Bitmap.createScaledBitmap(bitmapList[0], scaleSize, scaleSize*2+border, false)
                    val _p32 = Bitmap.createScaledBitmap(bitmapList[1], scaleSize, scaleSize, false)
                    val _p33 = Bitmap.createScaledBitmap(bitmapList[2], scaleSize, scaleSize, false)
                    // 绘图
                    drawRoundBitmap1(
                        canvas,
                        _p31,
                        0,
                        0,
                        scaleSize,
                        scaleSize*2+border,
                        radius
                    )
                    drawRoundBitmap(canvas, _p32, border + scaleSize, 0, scaleSize, radius)
                    drawRoundBitmap(
                        canvas,
                        _p33,
                        border + scaleSize,
                        border + scaleSize,
                        scaleSize,
                        radius
                    )
                }
                4 -> {
                    // 比例缩放
                    val _p41 = Bitmap.createScaledBitmap(bitmapList[0], scaleSize, scaleSize, false)
                    val _p42 = Bitmap.createScaledBitmap(bitmapList[1], scaleSize, scaleSize, false)
                    val _p43 = Bitmap.createScaledBitmap(bitmapList[2], scaleSize, scaleSize, false)
                    val _p44 = Bitmap.createScaledBitmap(bitmapList[3], scaleSize, scaleSize, false)
                    // 绘图
                    drawRoundBitmap(canvas, _p41, 0, 0, scaleSize, radius)
                    drawRoundBitmap(canvas, _p42, border  + scaleSize, 0, scaleSize, radius)
                    drawRoundBitmap(canvas, _p43, 0, border  + scaleSize, scaleSize, radius)
                    drawRoundBitmap(
                        canvas,
                        _p44,
                        border  + scaleSize,
                        border  + scaleSize,
                        scaleSize,
                        radius
                    )
                }
                else -> {
                }
            }
            result
        } catch (e: Exception) {
            null
        } finally {
//            for (bitmap in bitmapList) {
//                bitmap.recycle()
//            }
        }
    }
}